package cn.cjlmonster.hyouka_assistant.webView

import android.Manifest
import android.app.Activity
import android.graphics.Bitmap
import android.net.Uri
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebView
import androidx.activity.result.ActivityResultCaller
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import java.io.File
import java.io.FileOutputStream


/**
 * CustomWebChromeClient
 *
 * @author cjl
 * @date 2024/4/30 10:04
 */
open class CustomWebChromeClient(caller: ActivityResultCaller) : WebChromeClient() {

    private val currentActivity: AppCompatActivity = when (caller is Activity) {
        true -> caller as AppCompatActivity
        false -> (caller as Fragment).activity as AppCompatActivity
    }

    private val launchCameraPermission =
        caller.registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            if (it) {
                takePhoto()
            } else {
                uploadCallback?.onReceiveValue(arrayOf())
            }
        }

    private val launchPictures =
        caller.registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia()) {
            if (it.isNotEmpty()) {
                uploadCallback?.onReceiveValue(it.toTypedArray())
            } else uploadCallback?.onReceiveValue(arrayOf())
        }

    private val launchCamera =
        caller.registerForActivityResult(ActivityResultContracts.TakePicturePreview()) {
            if (it == null) {
                uploadCallback?.onReceiveValue(arrayOf())
            } else {
                val uri = Uri.fromFile(saveTempBitmap(it))
                uploadCallback?.onReceiveValue(arrayOf(uri))
            }
        }

    private var uploadCallback: ValueCallback<Array<Uri>>? = null

    override fun onShowFileChooser(
        webView: WebView?,
        filePathCallback: ValueCallback<Array<Uri>>?,
        fileChooserParams: FileChooserParams?
    ): Boolean {
        uploadCallback = filePathCallback
        when (fileChooserParams!!.isCaptureEnabled) {
            true -> checkCameraPermission()
            false -> selectPictures()
        }
        return true
    }

    private fun checkCameraPermission() {
        launchCameraPermission.launch(Manifest.permission.CAMERA)
    }

    private fun takePhoto() = launchCamera.launch(null)

    private fun selectPictures() =
        launchPictures.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageAndVideo))

    private fun saveTempBitmap(bm: Bitmap): File {
        val f = File(currentActivity.cacheDir, System.currentTimeMillis().toString() + ".jpg")
        try {
            if (f.exists()) f.delete()
            val out = FileOutputStream(f)
            bm.compress(Bitmap.CompressFormat.JPEG, 100, out)
            out.flush()
            out.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return f
    }

}